package com.hospital.datasource.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.hospital.datasource.config.TenantCodeConfig;
import com.hospital.datasource.config.ThreadContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class TenantInterceptor implements HandlerInterceptor {

    @Autowired
    private TenantCodeConfig tenantCodeConfig;
    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    private static final AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!StringUtils.isEmpty(tenantCodeConfig.getIgnoreUrl())&&checkUrl(request.getRequestURI(),tenantCodeConfig.getIgnoreUrl())){
            return true;
        }
        try{
            String hospitalCode=request.getHeader("hospitalCode");
            String tenantCode=tenantCodeConfig.getTenantCodeByTenantId(hospitalCode);
            if(StringUtils.isEmpty(tenantCode)){
                log.error("error info","can't get code to determine datasource");
                return false;
            }
            DynamicDataSourceContextHolder.push(tenantCode);
            dynamicRoutingDataSource.determineDataSource();
            ThreadContextHolder.push(tenantCode);
            return true;
        }catch (Exception ex){
            throw  ex;
        }
    }

    private boolean checkUrl(String requestURI,String ignoreUrl) {
        List<String> urlList = Arrays.asList(ignoreUrl.split(","));
        for (int i=0;i<urlList.size();i++){
            if(antPathMatcher.match(urlList.get(i),requestURI)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        DynamicDataSourceContextHolder.clear();
        ThreadContextHolder.clear();
    }
}
